var ns, UIAlbumBrowser, gdMap,imageHandle;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            id: 0,
            encrypId:'',
            deviceName: '',
            deviceNumber: '',
            location: '',
            startTime: '',
            userName: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            
        },
        standardlist: [],
        imglist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,
        maxuploadcount: CONFIG.maxuploadcount,
        standardStatus: 0,
        GPSLocation: '',
        finishLocation:'',
    },
    methods: {
        get_data: function () {
            var that = this;
            var options = {};
            options.Id = that.form.id;
            options.encrypId = that.form.encrypId;
            ns.post(options, function (succeed, data, err) {
                console.log(JSON.stringify(data));
                console.log(JSON.stringify(err));
                if (succeed) {
                    that.form = data.data;
                    that.standardlist = data.checkList;
                    var list=data.fileList;
                    list = list.map(res => {
                        res.url = res.imageUrl;
                        return res
                    })
                    that.imglist = list;
                    that.imgindex = data.fileList.length;
                    setTimeout(function () {
                        that.get_yinsi();
                    }, 500)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                command: 'App/Device/GetDeviceTaskData'
            });
        },
        do_save: function () {
            var that = this;
            if (that.form.enableUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.form.finishStatus == 2) { //异常
                api.confirm({
                    title: '提示',
                    msg: '当前结果异常,是否需要进行报事报修登记?',
                    buttons: ['报事报修', '直接完成']
                }, function (ret, err) {
                    var ServiceStatus = -1;
                    if (ret.buttonIndex == 1) {
                        ServiceStatus = 1;
                    } else if (ret.buttonIndex == 2) {
                        ServiceStatus = 0;
                    }
                    if (ServiceStatus > -1) {
                        that.do_save_process(ServiceStatus);
                    }
                });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function () {
            api.sendEvent({
                name: 'devicetaskcomplete',
            });
        },
        do_save_process: function (ServiceStatus) {
            var that = this;
            var options = {};
            // options.action = "saveequipmenttaskdevicedata";
            options.Id = that.form.id;
            options.checkList = JSON.stringify(that.standardlist);
            options.finishStatus = that.form.finishStatus;
            options.finishLocation = that.finishLocation;
            options.remark = that.form.remark;
            options.TaskCompleteContent = that.form.TaskCompleteContent;
            var files = {};
            for (var i = 0; i < that.imglist.length; i++) {
                files['file' + i] = that.imglist[i].url
            }
            console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                console.log(JSON.stringify(data));
                console.log(JSON.stringify(err));
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    if (ServiceStatus == 1) {
                        setTimeout(function () {
                            ns.openWin('neibubaoshi_add_frm', '内部报事');
                        }, 500);
                        setTimeout(function () {
                            api.closeWin();
                        }, 510)
                    }
                    setTimeout(function () {
                        api.closeWin();
                    }, 1000)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: files,
                command: 'App/Device/CompleteTask'
            });
        },
        select_active: function (item, CheckStatus) {
            var that = this;
            console.log(JSON.stringify(item));
            if (that.form.TaskStatus == 3) {
                return;
            }
            item.status = CheckStatus;
            var isallnormal = true;
            for (var i = 0; i < that.standardlist.length; i++) {
                if (that.standardlist[i].status == 2) {
                    isallnormal = false;
                }
            }
            if (isallnormal) {
                this.form.finishStatus = 1;
                that.standardStatus = 1;
            } else {
                this.form.finishStatus = 2;
                that.standardStatus = 2;
            }
        },
        select_all_active: function (CheckStatus) {
            var that = this;
            if (that.form.status == 3) {
                return;
            }
            that.standardStatus = 1;
            for (let index = 0; index < that.standardlist.length; index++) {
                if (that.standardlist[index].finishStatus == 2) {
                    that.standardStatus = 2;
                    return;
                }
            }
            that.form.finishStatus = CheckStatus;
        },


        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath
                    });
                    that.imgindex++;
                }
            });
            return;
        },
        UIAlbumBrowser_transPath: function () {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function (ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath
                    });
                    that.imgindex++;
                }
            });
        },

        remove_img: function (index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                    if (item.ID > 0) {
                        that.do_remove_uploadimg(item);
                    }
                }
            }
        },
        do_remove_uploadimg: function (item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function (succeed, data, err) { });
        },
        // StartBmap: function () {
        //     var that = this;
        //     if (that.form.TaskStatus == 3) {
        //         return;
        //     }
        //     ns.confirmPer('location', function () {
        //         that.StartLocation();
        //     })
        // },
        // StartLocation: function () {
        //     var that = this;
        //     if (that.form.TaskStatus == 3) {
        //         return;
        //     }
        //     var num = 0; //次数
        //     that.form.GPSLocation = '';
        //     bmLocation.stopLocation();
        //     bmLocation.singleLocation({
        //         reGeocode: true,
        //         netWorkState: true
        //     }, function (ret) {
        //         if (ret.status) {
        //             that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
        //                 ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber;
        //         }
        //     });
        // },
        // configManager: function () {
        //     bmLocation.configManager({
        //         accuracy: 'hight_accuracy',
        //         filter: 1,
        //         activityType: 'automotiveNavigation',
        //         coordinateType: 'BMK09LL',
        //         locationTimeout: 10,
        //         reGeocodeTimeout: 10
        //     });
        // },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        get_yinsi:function(){
            var that=this;
            gdMap.updateMapViewPrivacy({
                privacyAgree:'didAgree',
                privacyShow:'didShow',
                containStatus:'didContain'
            });
            gdMap.updateSearchPrivacy({
                privacyAgree:'didAgree',
                privacyShow:'didShow',
                containStatus:'didContain'
            });
            that.getLocationLocal();
            
        },
        getLocationLocal: function () {
            var that=this;
            gdMap.getLocation({
                autoStop: true,
            }, function (ret, err) {
                if (ret.status) {
                    lat = ret.lat;
                    lon = ret.lon;
                    that.getNameFromCoords(lat,lon);
                }
            });
        },
        getNameFromCoords:function(lat,lon){
            var that=this;
            gdMap.getNameFromCoords({
                lon: lon,
                lat: lat
            }, function(ret, err) {
                if (ret.status) {
                    that.finishLocation=ret.address;
                    console.log(JSON.stringify(that.finishLocation));
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
    }
});
apiready = function () {
    api.parseTapmode();
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    // bmLocation = api.require('bmLocation');
    gdMap = api.require('aMap');
    imageHandle = api.require('imageHandle');

    ns = window.Foresight.Util;
    app.form.id = api.pageParam.id || 0;
    app.form.encrypId=api.pageParam.encrypId || '';
    // console.log(JSON.stringify(app.form.encrypId));
    toast = new auiToast();
    

    setTimeout(function () {
        app.get_data();
    }, 500)
    api.addEventListener({
        name: 'do_close_equdetail'
    }, function () {
        api.closeWin();
    });
    
    
    
}
